<!-- src/views/Borrow.vue -->
<template>
  <div>
    <el-container>
      <el-header>
        <div class="header-content">
          <h2>借阅管理</h2>
          <div>
            <el-button type="primary" @click="handleBack">
              <i class="bi bi-arrow-left"></i> 返回
            </el-button>
          </div>
        </div>
      </el-header>
      <el-main>
        <el-card shadow="hover">
          <el-spin :loading="loading" tip="加载中...">
            <el-table v-if="borrowRecords.length > 0" :data="borrowRecords" style="width: 100%" stripe>
              <el-table-column prop="id" label="ID" width="50"></el-table-column>
              <el-table-column prop="username" label="用户"></el-table-column>
              <el-table-column prop="title" label="图书"></el-table-column>
              <el-table-column prop="borrow_date" label="借出时间"></el-table-column>
              <el-table-column prop="return_date" label="归还时间"></el-table-column>
              <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                  <el-tag :type="row.status === 'borrowed' ? 'warning' : 'success'">
                    {{ row.status === 'borrowed' ? '已借出' : '已归还' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200">
                <template #default="{ row }">
                  <div class="button-group">
                    <el-button size="mini" type="success" @click="returnBook(row.id)" :disabled="row.status !== 'borrowed'">
                      <i class="bi bi-check-circle-fill"></i> 归还
                    </el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="no-data">
              <el-empty description="暂无数据"></el-empty>
            </div>
          </el-spin>

          <!-- 分页组件 -->
          <div class="pagination-container" v-if="total > 0">
            <el-pagination
              background
              layout="prev, pager, next, jumper"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="total"
              @current-change="handlePageChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from 'vue-router';

export default {
  name: 'Borrow',
  setup() {
    const router = useRouter();
    const borrowRecords = ref([]);
    const loading = ref(false);
    const currentPage = ref(1);
    const pageSize = ref(10);
    const total = ref(0);

    const user = JSON.parse(localStorage.getItem('user')) || { role: 'admin', username: 'admin', id: 1 };

    /**
     * 获取借阅记录（服务端分页）
     */
    const fetchBorrowRecords = () => {
      loading.value = true;
      axios
        .get(`/api/borrow_records?page=${currentPage.value}&limit=${pageSize.value}`)
        .then((response) => {
          if (response.data.borrow_records && typeof response.data.total === 'number') {
            // 后端返回 { borrow_records: [...], total: number }
            borrowRecords.value = response.data.borrow_records.map(record => ({
              id: record.id,
              username: record.username,
              title: record.title,
              borrow_date: formatDate(record.borrow_date),
              return_date: record.return_date ? formatDate(record.return_date) : '未归还',
              status: record.status,
            }));
            total.value = response.data.total;
            loading.value = false;
          } else {
            ElMessage.error('获取借阅记录失败，响应格式不正确');
            loading.value = false;
          }
        })
        .catch((error) => {
          console.error('获取借阅记录失败:', error);
          ElMessage.error('获取借阅记录失败');
          loading.value = false;
        });
    };

    /**
     * 格式化日期
     */
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      return date.toLocaleString();
    };

    /**
     * 归还图书
     */
    const returnBook = (borrowId) => {
      ElMessageBox.confirm('确定归还这本图书吗?', '确认归还', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const payload = {
            borrow_id: borrowId,
            username: user.username, // 当前操作人
          };

          axios
            .post('/api/return', payload)
            .then((response) => {
              if (response.data.success) {
                ElMessage.success(response.data.message || '归还成功');
                fetchBorrowRecords();
              } else {
                ElMessage.error(response.data.message || '归还失败');
              }
            })
            .catch((error) => {
              console.error('归还图书失败:', error);
              ElMessage.error('归还图书失败');
            });
        })
        .catch(() => {
          // 用户取消归还
        });
    };

    /**
     * 返回仪表盘
     */
    const handleBack = () => {
      router.push('/dashboard');
    };

    /**
     * 分页切换
     */
    const handlePageChange = (page) => {
      currentPage.value = page;
      fetchBorrowRecords(); // 切换页码后重新请求后端
    };

    onMounted(() => {
      fetchBorrowRecords();
    });

    return {
      borrowRecords,
      loading,
      handleBack,
      currentPage,
      pageSize,
      total,
      handlePageChange,
      returnBook,
    };
  },
};
</script>

<style scoped>
.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 60px;
  padding: 0 20px;
}

.el-header {
  background-color: #409eff;
  color: white;
}

.button-group {
  display: flex;
  gap: 5px;
  flex-wrap: nowrap;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
